package com.swm.yzgrtk;

import com.fazecast.jSerialComm.SerialPort;
import com.swm.yzgrtk.utils.DataTransUtil;
import com.swm.yzgrtk.utils.DialogUtil;
import com.swm.yzgrtk.utils.MapTransFile;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import org.apache.shiro.codec.Base64;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.swm.yzgrtk.utils.GpsUtil.getGPSData;


public class RtkController {

    @FXML
    private Pane barchart;
    static String[] bauds = {"110", "300", "600", "1200", "2400", "4800", "9600", "14400", "19200", "38400", "56000", "57600", "115200", "128000", "230400", "256000", "460800", "500000", "512000", "600000", "750000", "921600", "1000000", "1500000", "2000000"};
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:sss");

    @FXML
    private TextArea localtionrecv;
    @FXML
    private Button ltrecvascii;
    @FXML
    private Button ltrecvahex;
    private static String gga = null;

    @FXML
    private TextArea localtionsend;
    @FXML
    private Button ltsendascii;
    @FXML
    private Button ltsendhex;
    SerialPort serialPortLt;
    @FXML
    private Button ltsend;
    SerialPort serialPortFg;
    String recvlt = "";
    TreeMap<Integer, Integer> gsvmap = new TreeMap<>();
    @FXML
    private Pane comchecklt;
    @FXML
    private Pane comcheckfg;

    @FXML
    private TextField at1text;
    @FXML
    private TextField at2text;
    @FXML
    private TextField at3text;
    @FXML
    private TextField at4text;
    @FXML
    private TextField at5text;
    @FXML
    private TextField at6text;
    @FXML
    private TextField at7text;
    @FXML
    private TextField at8text;
    @FXML
    private TextField at9text;
    @FXML
    private TextField at10text;
    @FXML
    private TextField at11text;
    @FXML
    private TextField at12text;
    @FXML
    private TextField at13text;
    @FXML
    private TextField at14text;
    @FXML
    private TextField at15text;


    @FXML
    private Button clearltrecv;
    @FXML
    private Button clearltsend;
    @FXML
    private Label longitude;
    @FXML
    private Label latitude;
    @FXML
    private Label hdop;


    @FXML
    private Button at1;
    @FXML
    private Button at2;
    @FXML
    private Button at3;
    @FXML
    private Button at4;
    @FXML
    private Button at5;
    @FXML
    private Button at6;
    @FXML
    private Button at7;
    @FXML
    private Button at8;
    @FXML
    private Button at9;
    @FXML
    private Button at10;
    @FXML
    private Button at11;
    @FXML
    private Button at12;
    @FXML
    private Button at13;
    @FXML
    private Button at14;
    @FXML
    private Button at15;


    @FXML
    private Label dpop;
    @FXML
    private Label locationstatus;


    @FXML
    private TextArea fgrecv;
    @FXML
    private Button fgrecvascii;
    @FXML
    private Button fgrecvhex;
    @FXML
    private Button savecommond;
    @FXML
    private Button sendAt;


    @FXML
    private TextArea fgsend;
    @FXML
    private Button fgsendascii;
    @FXML
    private Button fgsendhex;


    @FXML
    private TextField ntripaccount;
    @FXML
    private TextField ntrippassword;
    @FXML
    private TextArea ntriptrans;
    @FXML
    private Button trans;

    @FXML
    private Button clearfgrecv;
    @FXML
    private Button clearfgsend;
    @FXML
    private Button fgsendbt;
    //表示待发送AT
    private int step = 0;

    private static String projectPath = System.getProperty("user.dir");

    public static String bytesToBinary(byte[] bytes) {
        StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            // 将字节转换为无符号的整数，然后转换为二进制字符串
            int unsignedByte = b & 0xFF; // 确保是正数
            String binaryStr = Integer.toBinaryString(unsignedByte);
            // 确保二进制字符串长度为8
            binary.append(String.format("%8s", binaryStr).replace(' ', '0'));
        }
        return binary.toString();
    }

    @FXML
    public void initialize() {
        localtionrecv.setStyle("-fx-text-inner-color:#1CCC1C;");
        localtionrecv.setPromptText("串口接收数据显示区");
        localtionsend.setPromptText("串口发送数据显示区");
        fgrecv.setPromptText("串口接收数据显示区");
        fgsend.setPromptText("串口发送数据显示区");

        //定位模块接收区
        ltrecvascii.setDisable(true);
        ltrecvascii.setOnMouseClicked(e->{
            ltrecvascii.setDisable(true);
            ltrecvahex.setDisable(false);
            String text = localtionrecv.getText();
            String ascii = DataTransUtil.hexToAscii(text);
            localtionrecv.setText(ascii);
        });
        ltrecvahex.setOnMouseClicked(e->{
            ltrecvahex.setDisable(true);
            ltrecvascii.setDisable(false);
            String text = localtionrecv.getText();
            String hex = DataTransUtil.asciiToHex(text);
            localtionrecv.setText(hex);
        });
        clearltrecv.setOnMouseClicked(e -> localtionrecv.clear());

        //定位模块发送区
        ltsendascii.setDisable(true);
        ltsendascii.setOnMouseClicked(e->{
            ltsendhex.setDisable(false);
            ltsendascii.setDisable(true);
            String text = localtionsend.getText();
            String ascii = DataTransUtil.hexToAscii(text);
            localtionsend.setText(ascii);
        });

        ltsendhex.setOnMouseClicked(e->{
            ltsendhex.setDisable(true);
            ltsendascii.setDisable(false);
            String text = localtionsend.getText();
            String hex = DataTransUtil.asciiToHex(text);
            localtionsend.setText(hex);
        });
        clearltsend.setOnMouseClicked(e -> localtionsend.clear());
        ltsend.setOnMouseClicked(e -> serialPortLt.writeBytes(localtionsend.getText().getBytes(), localtionsend.getText().getBytes().length));


        //4G模块接收区
        fgrecvascii.setDisable(true);
        fgrecvascii.setOnMouseClicked(e -> {
            fgrecvhex.setDisable(false);
            fgrecvascii.setDisable(true);

            String text = fgrecv.getText();
            String ascii = DataTransUtil.hexToAscii(text);
            fgrecv.setText(ascii);
        });

        fgrecvhex.setOnMouseClicked(e -> {
            fgrecvhex.setDisable(true);
            fgrecvascii.setDisable(false);
            String text = fgrecv.getText();
            String hex = DataTransUtil.asciiToHex(text);
            fgrecv.setText(hex);
        });
        clearfgrecv.setOnMouseClicked(e -> fgrecv.clear());


        //4G模块发送区
        fgsendascii.setDisable(true);
        fgsendascii.setOnMouseClicked(e -> {
            fgsendhex.setDisable(false);
            fgsendascii.setDisable(true);
        });

        fgsendhex.setOnMouseClicked(e -> {
            fgsendhex.setDisable(true);
            fgsendascii.setDisable(false);
        });

        clearfgsend.setOnMouseClicked(e -> fgsend.clear());
        fgsendbt.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                //serialPortFg.writeBytes(fgsend.getText().getBytes(), fgsend.getText().getBytes().length);
                sendGetPoint();
            }
        });


        Map<String, String> map = MapTransFile.importMap(projectPath+"/mainset.properties");
        if (map == null) {
            map = new HashMap<>();
            MapTransFile.updatePro(map, projectPath+"/mainset.properties");
        }

        at1text.setText(map.get("AT1"));
        at2text.setText(map.get("AT2"));
        at3text.setText(map.get("AT3"));
        at4text.setText(map.get("AT4"));
        at5text.setText(map.get("AT5"));
        at6text.setText(map.get("AT6"));
        at7text.setText(map.get("AT7"));
        at8text.setText(map.get("AT8"));
        at9text.setText(map.get("AT9"));
        at10text.setText(map.get("AT10"));
        at11text.setText(map.get("AT11"));
        at12text.setText(map.get("AT12"));
        at13text.setText(map.get("AT13"));
        at14text.setText(map.get("AT14"));
        at15text.setText(map.get("AT15"));
        ntripaccount.setText(map.get("ntripaccount"));
        ntrippassword.setText(map.get("ntrippassword"));
        ntriptrans.setText(map.get("ntripbase64"));

        at1.setOnMouseClicked(e->{
            String text = at1text.getText();
            sendAt(text);
        });

        at2.setOnMouseClicked(e->{
            String text = at2text.getText();
            sendAt(text);
        });

        at3.setOnMouseClicked(e->{
            String text = at3text.getText();
            sendAt(text);
        });

        at4.setOnMouseClicked(e->{
            String text = at4text.getText();
            sendAt(text);
        });

        at5.setOnMouseClicked(e->{
            String text = at5text.getText();
            sendAt(text);
        });

        at6.setOnMouseClicked(e->{
            String text = at6text.getText();
            sendAt(text);
        });

        at7.setOnMouseClicked(e->{
            String text = at7text.getText();
            sendAt(text);
        });

        at8.setOnMouseClicked(e->{
            String text = at8text.getText();
            sendAt(text);
        });

        at9.setOnMouseClicked(e->{
            String text = at9text.getText();
            sendAt(text);
        });

        at10.setOnMouseClicked(e->{
            String text = at10text.getText();
            sendAt(text);
        });

        at11.setOnMouseClicked(e -> {
            String text = at11text.getText();
            sendAt(text);
        });

        at12.setOnMouseClicked(e -> {
            String text = at12text.getText();
            sendAt(text);
        });

        at13.setOnMouseClicked(e -> {
            String text = at13text.getText();
            sendAt(text);
        });

        at14.setOnMouseClicked(e -> {
            String text = at14text.getText();
            sendAt(text);
        });

        at15.setOnMouseClicked(e -> {
            String text = at15text.getText();
            sendAt(text);

        });
        //保存命令
        savecommond.setOnMouseClicked(e -> {
            Map<String, String> mapCommond = new HashMap<>();
            if (at1text.getText() != null) {
                mapCommond.put("AT1", at1text.getText());
            }
            if (at2text.getText() != null) {
                mapCommond.put("AT2", at2text.getText());
            }
            if (at3text.getText() != null) {
                mapCommond.put("AT3", at3text.getText());
            }
            if (at4text.getText() != null) {
                mapCommond.put("AT4", at4text.getText());
            }
            if (at5text.getText() != null) {
                mapCommond.put("AT5", at5text.getText());
            }
            if (at6text.getText() != null) {
                mapCommond.put("AT6", at6text.getText());
            }
            if (at7text.getText() != null) {
                mapCommond.put("AT7", at7text.getText());
            }
            if (at8text.getText() != null) {
                mapCommond.put("AT8", at8text.getText());
            }
            if (at9text.getText() != null) {
                mapCommond.put("AT9", at9text.getText());
            }
            if (at10text.getText() != null) {
                mapCommond.put("AT10", at10text.getText());
            }
            if (at11text.getText() != null) {
                mapCommond.put("AT11", at11text.getText());
            }
            if (at12text.getText() != null) {
                mapCommond.put("AT12", at12text.getText());
            }
            if (at13text.getText() != null) {
                mapCommond.put("AT13", at13text.getText());
            }
            if (at14text.getText() != null) {
                mapCommond.put("AT14", at14text.getText());
            }
            if (at15text.getText() != null) {
                mapCommond.put("AT15", at15text.getText());
            }

            MapTransFile.updatePro(mapCommond, projectPath+"/mainset.properties");

            DialogUtil.showDialog("保存成功");

        });
        sendAt.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                sendAt("AT");
            }
        });

        trans.setOnMouseClicked(e -> {

            if (ntripaccount.getText()==null||ntrippassword.getText()==null){
                DialogUtil.showDialog("请正确填写ntrip账户密码");
                return;
            }
            String base64 = Base64.encodeToString((ntripaccount.getText() + ":" + ntrippassword.getText()).getBytes());
            Map<String, String> mapntrip = new HashMap<>();
            mapntrip.put("ntripaccount",ntripaccount.getText());
            mapntrip.put("ntrippassword",ntrippassword.getText());
            mapntrip.put("ntripbase64",base64);
            MapTransFile.updatePro(mapntrip,projectPath+"/mainset.properties");

            ntriptrans.setText(base64);
        });


        //定位模块头部

        SerialPort[] commPorts = SerialPort.getCommPorts();
        ComboBox<String> periDiaCblt = new ComboBox<>();
        if (commPorts.length > 0) {

            periDiaCblt.setPrefWidth(100);
            periDiaCblt.setValue(commPorts[0].getSystemPortName());
            periDiaCblt.setOnMouseClicked(e -> {
                ArrayList<String> coms = new ArrayList<>();
                SerialPort[] commPor = SerialPort.getCommPorts();
                for (SerialPort serialPort : commPor) {
                    coms.add(serialPort.getSystemPortName());
                }
                periDiaCblt.getItems().clear();
                periDiaCblt.getItems().addAll(coms);
            });
        }


        ComboBox<String> baudlt = new ComboBox<>();
        baudlt.setPrefWidth(100);
        baudlt.setValue("115200");
        baudlt.getItems().addAll(bauds);

        Button openlt = new Button("打开");
        openlt.setLayoutX(110);
        openlt.setOnMouseClicked(e -> {
            SerialPort[] commPor = SerialPort.getCommPorts();
            String selectedItem = periDiaCblt.getValue();
            for (SerialPort serialPort : commPor) {
                if (serialPort.getSystemPortName().equals(selectedItem)) {
                    serialPortLt = serialPort;
                    serialPortLt.setBaudRate(Integer.parseInt(baudlt.getValue())); // 设置波特率
                    boolean openflag = serialPortLt.openPort();// 打开串口
                    if (openflag) {
                        DialogUtil.showDialog("打开串口成功");
                        openlt.setDisable(true);
                    } else {
                        DialogUtil.showDialog("打开串口失败，请检查串口状态");
                    }

                    new Thread(() -> {
                        while (true) {
                            if (serialPortLt.bytesAvailable() > 0) {
                                try {
                                    byte[] readBuffer = new byte[serialPortLt.bytesAvailable()];
                                    int numRead = serialPortLt.readBytes(readBuffer, readBuffer.length);
                                    String data = new String(readBuffer, 0, numRead);
                                    recvlt = recvlt.concat(data);
                                    String[] split3 = recvlt.split("GGA");
                                    if (split3.length > 3) {

                                        if (data.contains("GGA,")) {
                                            String[] split1 = data.split("GGA,");
                                            String s = split1[1];
                                            String s1 = s.split("\r\n")[0];
                                            String[] split = s1.split(",");

                                            if (split.length > 13) {
                                                if (serialPortFg != null) {
                                                    //GGA发生变化
                                                    gga = "$BDGGA," + s1;
                                                    Platform.runLater(() -> {
                                                        System.out.println("定位模块向4g模块发送：" + gga);
                                                        String concat = gga.concat("\r\n");
                                                        int length = concat.length();
                                                        int i = serialPortFg.writeBytes(concat.getBytes(), concat.length());
                                                    });
                                                }


                                                double[] gpsData = getGPSData(split[3], split[1]);
                                                /* 经度 */
                                                BigDecimal bgLongitude = BigDecimal.valueOf(gpsData[0]);
                                                double dlongitude = bgLongitude.setScale(10, RoundingMode.HALF_UP).doubleValue();
                                                /* 纬度 */
                                                BigDecimal bglatitude = BigDecimal.valueOf(gpsData[1]);
                                                double dlatitude = bglatitude.setScale(10, RoundingMode.HALF_UP).doubleValue();
                                                //定位状态
                                                int status = Integer.parseInt(split[5]);
                                                String statusStr;

                                                switch (status) {
                                                    case 1:
                                                        statusStr = "单点定位";
                                                        break;
                                                    case 2:
                                                        statusStr = "码差分";
                                                        break;
                                                    case 3:
                                                        statusStr = "无效PPS";
                                                        break;
                                                    case 4:
                                                        statusStr = "固定解";
                                                        break;
                                                    case 5:
                                                        statusStr = "浮点解";
                                                        break;

                                                    case 6:
                                                        statusStr = "正在估算";
                                                        break;
                                                    case 7:
                                                        statusStr = "人工输入固定值";
                                                        break;
                                                    case 8:
                                                        statusStr = "模拟模式";
                                                        break;
                                                    case 9:
                                                        statusStr = "WAAS差分";
                                                        break;

                                                    case 0:
                                                    default:
                                                        statusStr = "未定位";
                                                        break;
                                                }


                                                //HDOP水平精度因子
                                                //String s3 = split[7];

                                                Platform.runLater(() -> {
                                                    longitude.setText(String.valueOf(dlongitude));
                                                    // 你的UI更新代码
                                                    latitude.setText(String.valueOf(dlatitude));
                                                    locationstatus.setText(statusStr);
                                                    localtionrecv.appendText(sdf.format(new Date()) + "\n" + data + "\n");
                                                });
                                            }

                                        }

                                        if (data.contains("GSV,")) {

                                            String[] split1 = data.split("GSV,");
                                            for (int i = 1; i < split1.length; i++) {
                                                String[] split = split1[i].split("\n");
                                                String[] split2 = split[0].split(",");
                                                int i1 = split2.length - 4;
                                                if (i1 % 4 == 0) {
                                                    int i2 = i1 / 4;
                                                    for (int j = 0; j < i2; j++) {
                                                        gsvmap.put(Integer.parseInt(split2[j * 4 + 3]), Integer.parseInt(split2[j * 4 + 6]));
                                                    }
                                                }
                                            }
                                            Platform.runLater(() -> {
                                                final NumberAxis yAxis = new NumberAxis();//定义一个数字轴起名为y轴
                                                final CategoryAxis xAxis = new CategoryAxis();//定义一个分类轴起名为x轴
                                                final BarChart<String, Number> bc =
                                                        new BarChart<>(xAxis, yAxis);//创建一个柱状图(条形图)
                                                bc.setTitle("信噪比");//设置图的标题
                                                bc.setPrefWidth(600);
                                                bc.setPrefHeight(300);


                                                //yAxis.setLabel("信噪比");//设置y轴标签

                                                Series series = new Series();//创建数据序列1
                                                series.setName("信噪比");//序列标识
                                                if (gsvmap != null) {
                                                    gsvmap.forEach((k, v) -> {
                                                        series.getData().add(new XYChart.Data<>(String.valueOf(k), v));//设置数据序列值

                                                    });
                                                    bc.getData().addAll(series);//柱状图对象上挂载3个数据序列
                                                    barchart.getChildren().clear();
                                                    barchart.getChildren().add(bc);
                                                }

                                            });
                                        }
                                    }


                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }

                            } else {
                                try {
                                    Thread.sleep(100); // 减少CPU占用率
                                } catch (InterruptedException e1) {
                                    Thread.currentThread().interrupt(); // 恢复中断状态
                                }
                            }
                        }
                    }).start();
                    break;
                }
            }

        });
        Button closelt = new Button("关闭");
        closelt.setLayoutX(150);
        closelt.setOnMouseClicked(e -> {
            try {
                boolean closeflag = serialPortLt.closePort();
                if (closeflag) {
                    DialogUtil.showDialog("关闭串口成功");
                    openlt.setDisable(false);
                } else {
                    DialogUtil.showDialog("关闭串口失败，请检查串口状态");
                }

            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });

        HBox hBoxlt = new HBox(10); // 10像素间隔
        hBoxlt.setLayoutX(100); // 可以设置Pane内部的布局位置
        hBoxlt.setLayoutY(15);
        hBoxlt.getChildren().addAll(periDiaCblt, baudlt, openlt, closelt);
        comchecklt.getChildren().add(hBoxlt);


        //4G模块头部
        ComboBox<String> periDiaCbfg = new ComboBox<>();
        periDiaCbfg.setPrefWidth(100);
        periDiaCbfg.setValue(commPorts[0].getSystemPortName());
        periDiaCbfg.setOnMouseClicked(e -> {
            ArrayList<String> coms = new ArrayList<>();
            SerialPort[] commPor = SerialPort.getCommPorts();
            for (SerialPort serialPort : commPor) {
                coms.add(serialPort.getSystemPortName());
            }
            periDiaCbfg.getItems().clear();
            periDiaCbfg.getItems().addAll(coms);
        });

        ComboBox<String> baudfg = new ComboBox<>();
        baudfg.setPrefWidth(100);
        baudfg.setValue("115200");
        baudfg.getItems().addAll(bauds);

        Button openfg = new Button("打开");
        openfg.setLayoutX(110);
        openfg.setOnMouseClicked(e -> {
            SerialPort[] commPor = SerialPort.getCommPorts();
            String selectedItem = periDiaCbfg.getValue();
            for (SerialPort serialPort : commPor) {
                if (serialPort.getSystemPortName().equals(selectedItem)) {
                    serialPortFg = serialPort;
                    serialPortFg.setBaudRate(Integer.parseInt(baudfg.getValue())); // 设置波特率
                    boolean openflag = serialPortFg.openPort();// 打开串口
                    if (openflag) {
                        DialogUtil.showDialog("打开串口成功");
                        openfg.setDisable(true);
                    } else {
                        DialogUtil.showDialog("打开串口失败，请检查串口状态");
                    }

                    new Thread(() -> {
                        String recv = "";
                        while (true) {
                            if (serialPortFg.bytesAvailable() > 0) {
                                byte[] readBuffer = new byte[serialPortFg.bytesAvailable()];
                                //byte[] readBuffer = new byte[1024];
                                int numRead = serialPortFg.readBytes(readBuffer, readBuffer.length);
                                BigInteger bigInteger = new BigInteger(bytesToBinary(readBuffer), 2);
                                String string = bigInteger.toString(16);
                                if(serialPortLt!=null){
                                    serialPortLt.writeBytes(readBuffer, readBuffer.length);
                                }

                                /*if (string.startsWith("d300")) {
                                    recv = "";
                                    recv = string;
                                } else {
                                    recv = recv.concat(string);
                                }

                                String[] split = recv.split("d300");
                                for (int i = 1; i < split.length; i++) {
                                    String s = "d300" + split[i];

                                    String substring = s.substring(0, s.length() - 6);
                                    String crc24 = s.substring(s.length() - 6, s.length());
                                    byte[] bytes = hexStringToByteArray(substring);
                                    if (bytes != null) {
                                        String crc = Integer.toHexString(rtcmCrc24(bytes));
                                        while (crc.length() < 6) {
                                            crc = "0" + crc;
                                        }
                                        if (crc24.equals(crc)) {
                                            byte[] bytes2 = hexStringToByteArray(s);
                                            String data0 = new String(bytes2, 0, bytes2.length);
                                            if(serialPortLt!=null){
                                                System.out.println("校验成功，4g模块向定位模块发送："+s);
                                                String concat = data0.concat("\r\n");
                                                //serialPortLt.writeBytes(concat.getBytes(), data0.length());
                                                serialPortLt.writeBytes(bytes2, bytes2.length);
                                            }
                                        } else {
                                            System.out.println("校验失败");
                                        }
                                    }
                                }*/


                                String data = new String(readBuffer, 0, numRead);
                                //成功返回
                                if (data.contains("OK")) {
                                    step++;
                                    switch (step) {
                                        case 0:
                                            sendAt("AT");
                                            break;
                                        case 1:
                                            sendAt("AT+CSQ");
                                            break;
                                        case 2:
                                            sendAt("AT+CGMI");
                                            break;
                                        case 3:
                                            sendAt("AT+CGMM");
                                            break;
                                        case 4:
                                            sendAt("AT+CPIN?");
                                            break;
                                        case 5:
                                            sendAt("AT+CIMI");
                                            break;
                                        case 6:
                                            sendAt("AT+CGSN");
                                            break;
                                        case 7:
                                            sendAt("AT+CREG?");
                                            break;
                                        case 8:
                                            sendAt("AT+QIDEACT=1");
                                            break;
                                        case 9:
                                            sendAt("AT+QIACT=1");
                                            break;

                                        case 10:
                                            sendAt("AT+QICSGP=1,1,\"CTNET\",\"\",\"\",1");
                                            break;
                                        case 11:
                                            sendAt("AT+QICLOSE=0");
                                            break;
                                        case 12:
                                            step = 0;
                                            sendAt("AT+QIOPEN=1,0,\"TCP\",\"rtk.ntrip.qxwz.com\",8002,0,2");
                                            break;
                                        /*case 13:
                                            step = 0;
                                            sendAt("$GBGGA,060253.000,3448.228008,N,11331.777866,E,1,09,1.32,116.600,M,-16.325,M,,*5E");

                                            break;*/


                                    }
                                } else if (data.contains("CONNECT")) {
                                    sendGetPoint();
                                } else if (data.contains("ICY 200 OK")) {

                                } else if (data.contains("ERROR")) {
                                    // System.out.println(data);
                                }

                                Platform.runLater(() -> {
                                    fgrecv.appendText(sdf.format(new Date()) + "\n" + data + "\n");
                                });


                            } else {
                                try {
                                    Thread.sleep(300); // 减少CPU占用率
                                } catch (InterruptedException e1) {
                                    Thread.currentThread().interrupt(); // 恢复中断状态
                                }
                            }
                        }
                    }).start();
                    break;
                }
            }


        });
        Button closefg = new Button("关闭");
        closefg.setLayoutX(150);
        closefg.setOnMouseClicked(e -> {
            try {
                boolean closeflag = serialPortFg.closePort();
                if (closeflag) {
                    openfg.setDisable(false);
                    DialogUtil.showDialog("关闭串口成功");
                } else {
                    DialogUtil.showDialog("关闭串口失败，请检查串口状态");
                }

            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });

        HBox hBoxfg = new HBox(10); // 10像素间隔
        hBoxfg.setLayoutX(100); // 可以设置Pane内部的布局位置
        hBoxfg.setLayoutY(15);
        hBoxfg.getChildren().addAll(periDiaCbfg, baudfg, openfg, closefg);
        comcheckfg.getChildren().add(hBoxfg);
    }

    private void  sendAt(String command){
        if (serialPortFg == null) {
            DialogUtil.showDialog("串口尚未打开");
            return;
        }
        String concat = command.concat("\r\n");
        int length = concat.length();
        int i = serialPortFg.writeBytes(concat.getBytes(), concat.length());
    }

    private void sendGetPoint() {
        if (serialPortFg == null) {
            DialogUtil.showDialog("串口尚未打开");
            return;
        }
        Map<String, String> map = MapTransFile.importMap(projectPath+"/mainset.properties");
        String ntripbase64 = map.get("ntripbase64");

        String command = "GET /AUTO HTTP/1.0\r\n" +
                "User-Agent: NTRIP GNSSInternetRadio/1.4.10\r\n" +
                "Accept: */*\r\n" +
                "Connection: close\r\n" +
                "Authorization: Basic "+ntripbase64+"\r\n\r\n";
        ;


        int length = command.length();
        int i = serialPortFg.writeBytes(command.getBytes(), command.length());
    }

}